# -*- coding: utf-8 -*-
# @File     : services.py
# @Author   : bingjia
# @Time     : 2020/8/7 9:20
# @Desc     :

from datetime import timedelta
from collections import OrderedDict

from django.apps import apps
from django.utils import timezone
from django.db.models import Count, Q, Sum
from django.contrib.auth import get_user_model


def calculate_ratio(add_value, now_value):
    """
    计算新增比例
    """
    if add_value is None or now_value is None:
        add_value = now_value = 0
    return add_value / (now_value - add_value) if add_value != 0 and (now_value - add_value) != 0 else 0


def get_project_list_resources():
    """
    获取项目状态
    :return: list
    """
    resources = []
    project_model = apps.get_model("projects", "Project")
    project_queryset = project_model.objects.all()

    for project in project_queryset:
        resources.append({
            "name": project.name,
            "company": project.company,
            "location": project.location,
            "operation_date": project.operation_date
        })

    return resources


def get_total_public_resources():
    """
    获取数据状态
    :return: dict
    """
    resources = OrderedDict()

    today = timezone.now()
    yesterday = today - timedelta(days=1)
    seven_days_ago = yesterday - timedelta(days=7)

    user_model = get_user_model()
    data_model = apps.get_model("datas", "SrcData")
    check_model = apps.get_model("checks", "Defect")
    project_model = apps.get_model("projects", "Project")

    data_queryset = data_model.objects.all()
    check_queryset = check_model.objects.all()
    project_queryset = project_model.objects.all()
    user_queryset = user_model.objects.filter(is_active=True, is_system=False)

    resources["user_number"] = user_queryset.count()
    resources["project_number"] = project_queryset.count()
    resources["defect_image_number"] = check_queryset.count()
    resources["defect_type_number"] = check_queryset.values("defect").distinct().count()
    resources["visible_image_number"] = 0 if data_queryset.aggregate(nums=Sum('data_size'))["nums"] is None else data_queryset.aggregate(nums=Sum('data_size'))["nums"]
    resources["thermal_image_number"] = 0 if data_queryset.aggregate(nums=Sum('data_size'))["nums"] is None else data_queryset.aggregate(nums=Sum('data_size'))["nums"]

    resources["user_seven_add_ratio"] = calculate_ratio(
        user_queryset.filter(date_joined__range=(seven_days_ago, yesterday)).count(),
        user_queryset.count())

    resources["project_seven_add_ratio"] = calculate_ratio(
        project_queryset.filter(created_date__range=(seven_days_ago, yesterday)).count(),
        project_queryset.count())

    resources["defect_image_seven_add_ratio"] = calculate_ratio(
        check_queryset.filter(created_date__range=(seven_days_ago, yesterday)).count(),
        check_queryset.count())

    resources["defect_type_seven_add_ratio"] = calculate_ratio(
        check_queryset.filter(created_date__range=(seven_days_ago, yesterday)).values("defect").distinct().count(),
        check_queryset.values("defect").distinct().count())

    resources["visible_image_seven_add_ratio"] = calculate_ratio(
        data_queryset.filter(created_date__range=(seven_days_ago, yesterday)).aggregate(nums=Sum('data_size'))["nums"],
        data_queryset.aggregate(nums=Sum('data_size'))["nums"])

    resources["thermal_image_seven_add_ratio"] = calculate_ratio(
        data_queryset.filter(created_date__range=(seven_days_ago, yesterday)).aggregate(nums=Sum('data_size'))["nums"],
        data_queryset.aggregate(nums=Sum('data_size'))["nums"])

    return resources


def get_checks_public_resources():
    """
    获取缺陷状态
    :return:
    """
    resources = {}
    defect_type_model = apps.get_model("checks", "DefectType")
    defect_type_queryset = defect_type_model.objects.all()

    if defect_type_queryset:
        resources["defect"] = []
        for defect_type in defect_type_queryset:
            resources["defect"].append({
                "name": defect_type.name,
                "type": defect_type.type,
                "image": defect_type.image,
                "video": defect_type.video,
                "advice": defect_type.advice,
            })

    defect_model = apps.get_model("checks", "Defect")
    defect_queryset = defect_model.objects.all()

    check_defect_name = list(set([check.defect.name for check in defect_queryset]))
    if check_defect_name:
        resources["check"] = {
            "thermal": {
                "name": check_defect_name,
                "data": [defect_queryset.filter(defect__name=name).count() for name in check_defect_name]
            }}

    return resources


def get_infos_public_resources():
    """
    获取信息状态
    :return:
    """
    resourecs = []
    info_model = apps.get_model("infos", "Info")
    info_queryset = info_model.objects.filter(type="advice").all()

    for info in info_queryset:
        resourecs.append({
            "title": info.title,
            "content": info.content,
            "created_date": info.created_date

        })

    return resourecs



